package com.lebang.medicalInquiry.common;

import com.alibaba.fastjson.JSONObject;

import com.lebang.medicalInquiry.component.RedisComponent;
import com.lebang.medicalInquiry.constant.BusinessEnum;
import com.lebang.medicalInquiry.constant.RedisKeyEnum;
import com.lebang.medicalInquiry.mapper.OffLineNoticeMapper;
import com.lebang.medicalInquiry.model.po.OffLineNotice;
import com.lebang.medicalInquiry.model.vo.MessageModel;
import com.lebang.medicalInquiry.model.vo.OfflineNoticeVo;
import com.lebang.medicalInquiry.utils.TextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.xml.soap.Text;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @version V1.0
 * @author: zpc
 * @date:
 */
@Component
public class RedisKeyExpireTimeMonitor extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisComponent redisComponent;

    @Resource
    private OffLineNoticeMapper offLineNoticeMapper;

    /**
     * @param listenerContainer must not be {@literal null}.
     */
    public RedisKeyExpireTimeMonitor(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);

    }

    @Override
    protected void doRegister(RedisMessageListenerContainer listenerContainer) {
        Topic keyevent_expired_topic = new PatternTopic("__keyevent@1__:expired");
        listenerContainer.addMessageListener(this, keyevent_expired_topic);
    }

    /**
     * 把消息转存为离线消息
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        byte[] body = message.getBody();
        String key = new String(body, StandardCharsets.UTF_8);

        // 消息转为 离线消息
        if (key.startsWith(RedisKeyEnum.off_line_notice_expire.getName())) {
            // 取出 uuid
            String[] split = key.split(":");
            String messageId = split[1];
            String toUuid = split[2];
            // 获取被转化的离线消息
            Object value = redisComponent.getValue(RedisKeyEnum.off_line_notice_change_list.getName() + messageId + ":" + toUuid);
            // 查询当前用户是否存在离线聊天消息
            Object notice = redisComponent.getValue(RedisKeyEnum.off_line_notice.getName() + toUuid);
            // 获取用户的离线消息  key为聊天对象的uuid
            Map map = new HashMap();
            if (!TextUtil.isEmpty(notice)) {
                map = JSONObject.parseObject(notice.toString(), Map.class);
            }

            MessageModel messageModel = JSONObject.parseObject(value.toString(), MessageModel.class);

            // 当前被聊天用户的离线消息中是否包含聊天用户的离线信息
            Object memberOffLineNotice = map.get(messageModel.getFromUuid());
            OfflineNoticeVo offlineNoticeVo = new OfflineNoticeVo();
            if (TextUtil.isEmpty(memberOffLineNotice)) {
                offlineNoticeVo = new OfflineNoticeVo();
                offlineNoticeVo.setContent(messageModel.getContent());
                offlineNoticeVo.setUnReadCount(1);
                offlineNoticeVo.setTime(messageModel.getTime());
                offlineNoticeVo.setUserInfo(messageModel.getUserInfo());
                // 存储为离线消息

            } else {
                offlineNoticeVo = JSONObject.parseObject(memberOffLineNotice.toString(), OfflineNoticeVo.class);
                offlineNoticeVo.setContent(messageModel.getContent());
                offlineNoticeVo.setUnReadCount(offlineNoticeVo.getUnReadCount() + 1);
                offlineNoticeVo.setTime(messageModel.getTime());
                offlineNoticeVo.setUserInfo(messageModel.getUserInfo());

            }
            // 持久化离线消息
            OffLineNotice offLineNotice = new OffLineNotice();
            offLineNotice.setCreateTime(LocalDateTime.now());
            offLineNotice.setUpdateTime(LocalDateTime.now());
            offLineNotice.setHasDelete(0);
            offLineNotice.setState(1);
            offLineNotice.setChatJson(messageModel.toString());
            offLineNotice.setMessageId(messageModel.getMessageId());
            offLineNotice.setUuid(toUuid);
            offLineNotice.setChatUuid(messageModel.getFromUuid());
            offLineNoticeMapper.insertSelective(offLineNotice);
            map.put(messageModel.getFromUuid(), offlineNoticeVo);

            // 重新存储
            redisComponent.setExTimeValue(RedisKeyEnum.off_line_notice.getName() + toUuid, JSONObject.toJSON(map), 60 * 60 * 24 * 7);
            // 删除离线消息队列中的数据
            redisComponent.del(RedisKeyEnum.off_line_notice_change_list.getName() + messageId + ":" + toUuid);
        }

    }


}
